package com.yxq.mdt.app.modules.personal.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.convenientbanner.utils.ScreenUtil;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.hawk.Hawk;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.UmengShareHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.event.EventWxPay;
import com.yxq.mdt.app.modules.personal.adapter.RechargeItemListAdapter;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.bean.RechargeListBean;
import com.yxq.mdt.app.modules.personal.bean.RechargePayResultBean;
import com.yxq.mdt.app.modules.personal.bean.RechargeWxPayResultBean;
import com.yxq.mdt.app.modules.personal.model.MainPersonalModel;
import com.yxq.mdt.app.modules.personal.model.RechargeModel;
import com.yxq.mdt.app.modules.personal.presenter.IRechargeContract;
import com.yxq.mdt.app.modules.personal.presenter.RechargePresenter;
import com.yxq.mdt.app.modules.withdraw.bean.WithDrawResultBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.WXUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 充值蜜豆
 */
public class RechargeActivity extends BaseActivity<RechargePresenter> implements IRechargeContract.View {

    @BindView(R.id.sugar_tv_balance)
    TextView sugarTvBalance;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.sugar_btn_submit)
    Button sugarBtnSubmit;
    @BindView(R.id.sugar_tv_interval)
    TextView sugarTvInterval;
    @BindView(R.id.sugar_tv_proportion)
    TextView sugarTvProportion;
    RechargeItemListAdapter rechargeItemListAdapter;
    IWXAPI api;
    RechargeListBean rechargeListBean;
    @BindView(R.id.recharge_tv_service)
    TextView rechargeTvService;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constant.WECHAT_ID);
        mCommonTitleBar.setListener((v, action, extra) -> {
            if (action == CommonTitleBar.ACTION_LEFT_BUTTON) {
                finish();
            } else if (action == CommonTitleBar.ACTION_RIGHT_TEXT) {
                //明细
                startActivity(new Intent(mActivity, RechargeHistoryListActivity.class));
            }
        });
        rechargeItemListAdapter = new RechargeItemListAdapter(R.layout.item_recharge_list_layout, null);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 2));
        recyclerView.setAdapter(rechargeItemListAdapter);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, ScreenUtil.dip2px(mActivity, 15), false));
        rechargeItemListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                rechargeItemListAdapter.setCheckedPosition(position);
//                if (position == rechargeItemListAdapter.getItemCount() - 1) {
//
//                } else {
//                    hideSoftKeyBoard();
//                }
            }
        });
        MyPersonalBean bean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);// 不用科学计数
        sugarTvBalance.setText(String.format("%.2f", bean.getMoney()));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new RechargePresenter(this, new RechargeModel());
        mPresenter.selectPageInfoAndroid(1, 20);
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.sugar_btn_submit, R.id.recharge_tv_service})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sugar_btn_submit:
                //充值
                recharge();
                break;
            case R.id.recharge_tv_service:
                //跳转客服
                Intent intent = new Intent(mActivity, MainPersonalCustomerServiceAc.class);
                startActivity(intent);
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MainPersonalModel.getPersonalDate(Constant.getLbsUserToken(), new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean myPersonalBean) {
                sugarTvBalance.setText(String.format("%.2f", myPersonalBean.getMoney()));
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }

    private void recharge() {

//        if (rechargeItemListAdapter.getCheckedPosition() == rechargeItemListAdapter.getItemCount() - 1) {
//            //自定义数额
//            if (rechargeItemListAdapter.editText.getText().toString().trim().length() == 0) {
//                ToastUtils.showShort("请输入充值数额");
//                return;
//            }
//            long number = Long.parseLong(rechargeItemListAdapter.editText.getText().toString());
//            if (number < 100) {
//                ToastUtils.showShort("充值数额最低为100");
//                return;
//            }
//            if (number > 1000000) {
//                ToastUtils.showShort("充值数额最大为100万");
//                return;
//            }
//            if (number % 100 != 0) {
//                ToastUtils.showShort("充值数额必须为100的倍数");
//                return;
//            }
//
//            if (rechargeListBean != null && rechargeListBean.getCustom() != null) {
//                showLoadingDialog();
//                mPresenter.recharge(number, 1, rechargeListBean.getCustom().getId());
//            } else {
//                ToastUtils.showShort("暂时无法充值");
//            }
//            return;
//        }
        RechargeListBean.DataBean.ListBean listBean = rechargeItemListAdapter.getItem(rechargeItemListAdapter.getCheckedPosition());
        showLoadingDialog();
        mPresenter.recharge(listBean.getMoney(), 1, listBean.getId());
    }

    @Override
    public void onLoadSuccess(RechargeListBean data) {
        if (data != null && data.getData() != null && data.getData().getList() != null) {

//            data.getData().getList().add(new RechargeListBean.DataBean.ListBean());
            rechargeListBean = data;
        }
        rechargeItemListAdapter.setNewData(data.getData().getList());
    }

    @Override
    public void onLoadFailed(String msg) {

    }

    @Override
    public void onRechargeSuccess(RechargePayResultBean data) {
        hideLoadingDialog();
        if (data != null && data.getStatus() == 200) {
            showLoadingDialog();
            mPresenter.wxPay(data.getOrderId());
        } else {
            ToastUtils.showShort("操作失败");
        }
    }

    @Override
    public void onRechargeFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort("" + msg);
    }

    @Override
    public void onRechargeWxSuccess(RechargeWxPayResultBean data) {
        hideLoadingDialog();
        if (data != null) {
            //判断是否安装微信
            if (!UmengShareHelper.isWeChatAvailable(mActivity)) {
                ToastUtils.showShort("您尚未安装微信哦，请先安装微信");
                return;
            }
            PayReq req = new PayReq();

            req.appId = Constant.WECHAT_ID;//微信开放平台审核通过的应用APPID
            req.partnerId = Constant.WECHAT_MCH_ID;//微信支付分配的商户号
            req.prepayId = data.getPackageX().replaceAll("prepay_id=", "");//预支付交易会话ID
            req.nonceStr = data.getNonceStr();//随机字符串，不长于32位。
            req.timeStamp = data.getTimeStamp();//时间戳
            req.packageValue = "Sign=WXPay"; //扩展字段 暂填写固定值Sign=WXPay
            req.sign = WXUtil.genPayReq(req, data); //二次签名
            api.sendReq(req);
        }
    }

    @Override
    public void onRechargeWxFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort("" + msg);
    }

    @Override
    public void onCashdrillSuccess(WithDrawResultBean data) {

    }

    @Override
    public void onCashdrillFailed(String msg) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventWxPay message) {
        switch (message.code) {
            case 0://支付成功
                ToastUtils.showShort("支付成功");
                finish();
                break;
            case -1://支付失败
                ToastUtils.showShort("支付失败");
                break;
            case -2://取消成功
                ToastUtils.showShort("取消支付");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
